import { warn } from "vue"

export function validator(key: string, validator: any, values?: any[]): (val: any) => boolean {
  return (val: any) => {
    let err: string | undefined = ''
    if (validator) {
      err = validator(val)
      if (!err)
        return true
    }
    if (values) {
      if (values.includes(val)) {
        err = ''
      } else {
        const text = [...new Set(values)].map((value) => JSON.stringify(value)).join(', ')
        err = `one of [${text}]${err ? '' : ` or ${err}`}`
      }
    }
    if (err) {
      warn(`Invalid prop: validation failed for prop "${key}". Expected ${err},got value ${JSON.stringify(val)}`)
    }
    return true
  }
}